import express from "express"
// import { random } from "crypto"
import { random, authentication } from "../helpers"
import { getUserEmail, createUser } from "../db/users"

export const login = async (req: express.Request, res: express.Response) => {
  try {
    const { email, password } = req.body

    console.log(req.body)

    if (!email || !password) return res.sendStatus(400)

    const user = await getUserEmail(email)

    if (!user) return res.status(400).json({ message: 'User not found' })

    const exorctedHash = authentication(user.authentication.salt, password)

    if (exorctedHash !== user.authentication.password) {
      return res.status(400).json({ message: 'Incorrect password' })
    }

    const salt = random()
    user.authentication.sessionToken = authentication(salt, user._id.toString())

    await user.save()

    res.cookie('token', user.authentication.sessionToken, { domain: 'localhost', path: '/', httpOnly: true, secure: false })

    return res.status(200).json({ message: 'Login successful', user }).end()
    
  } catch (error) {
    console.log(error)
    return res.sendStatus(400)
  }
}

export const register = async (req: express.Request, res: express.Response) => {
  try {
    const { username, email, password } = req.body

    if (!username || !email || !password) return res.sendStatus(400)
    
    const existingUser = await getUserEmail(email)
    
    if (existingUser) {
      return res.status(400).json({ message: 'User already exists' })
    }

    const salt = random()

    const user = await createUser({
      username,
      email,
      authentication: { 
        password: authentication(salt, password), salt
      }
    })

    return res.status(200).json({ message: 'User created', user }).end()
    
  } catch (error) {
    console.log(error)
    return res.sendStatus(400)
  }
}
